import {toast} from "../../utils/tool";
import EventBus from "../../utils/eventBus";

const app = getApp();
Page({
    data: {
        order_id: 0,
        order: {},
        user: {},
        pay_type: 2,
        coupon_id: 0,
        coupon_sub: 0,
        vip_sub: 0,
        pay_price: 0,
        canUseNum: 0,
        couponList: [],
        activeCoupon: null,
        couponText: '',
        base_price: 0,
        couponMoney: 0,
    },
    getDate(time) {
        const date = new Date(time)
        const [year, month, day, hour, minute] = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()]
        return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}`
    },
    initCoupon() {
        app.ajax({
            url: "/api/user/coupons",
            data: {status: '1'},
            success: resp => {
                const {code, data, msg} = resp
                if (code !== 1) return toast({title: msg})
                const {pay_price} = this.data
                console.log(pay_price, 'pay_price')
                const list = data.map((item, index) => {
                    const {create_time, min} = item
                    const createTime = this.getDate(create_time * 1000)
                    return {
                        ...item,
                        createTime,
                        active: false,
                        disabled: Number(pay_price) < Number(min)
                    }
                })
                console.log('list==>', list)
                const canUse = list.filter(item => !item.disabled)
                console.log(canUse, 'canUse')
                this.setData({
                    couponText: `共有${list.length}张优惠券,可用${canUse.length}`,
                    couponList: list,
                    canUseNum: canUse.length
                })
            }
        })
    },
    useCoupon() {
        const {canUseNum} = this.data
        if (canUseNum === 0) return toast({title: '无可用优惠券'})
        wx.navigateTo({
            url: '/pages/chose-coupon/chose-coupon',
            success: event => {
                const {couponList, pay_price} = this.data
                event.eventChannel.emit('initData', {
                    list: couponList,
                    price: pay_price,
                    active: this.data.activeCoupon,
                })
            },
            events: {
                choseCoupon: res => {
                    const {order: {total_price}} = this.data
                    if (!!res) {
                        const {money} = res
                        const p = Number(total_price) - Number(money)
                        this.setData({
                            couponText: `使用${money}元优惠券`,
                            activeCoupon: res,
                            base_price: p > 0 ? p : 0,
                            couponMoney: Number(money)
                        })
                    } else {
                        this.setData({
                            couponText: `未使用优惠券`,
                            activeCoupon: null,
                            base_price: total_price,
                            couponMoney: 0
                        })
                    }
                }
            }
        })
    },
    pay_success: function () {
        const disclaimer = wx.getStorageSync('disclaimer');
        const that = this
        if (this.data.pay_type == 3) {
            wx.navigateTo({
                url: `/pages/meituan/meituan?num=${that.data.order.num}&orderID=${that.data.order_id}`
            })
            return false;
        }
        wx.showModal({
            title: '免责声明',
            content: disclaimer,
            cancelText: "取消",
            confirmText: "同意", //默认是“确定”
            success: function (res) {
                if (res.confirm) {//这里是点击了确定以后
                    wx.requestSubscribeMessage({
                        'tmplIds': [
                            'LPRQriYCiz0M_8SC1B35MxXwfF9NPR15rTO5UK7-V98',
                            'ILerHD6MYqAyGnyJ_AeVFSlqEMguQ24cTaT59Xot4Sw',
                            'mCcWRiaJcHNjX4A2WBu-ugdeD08yVZo7rFUBc5UptEc'
                            // 'ILerHD6MYqAyGnyJ_AeVFYMsR1yOg5GyeqpqAY6LQUY'
                        ],
                        complete: () => {
                            const {activeCoupon} = that.data
                            const params = {
                                order_id: that.data.order_id,
                                pay_type: that.data.pay_type
                            }
                            if (!!activeCoupon) {
                                params.coupon_id = activeCoupon.id
                            }
                            app.ajax({
                                url: '/api/user/pay',
                                data: params,
                                success: res => {
                                    if (res.code == 1) {
                                        if (res.data) {
                                            wx.requestPayment({
                                                nonceStr: res.data.nonceStr,
                                                package: res.data.package,
                                                paySign: res.data.paySign,
                                                timeStamp: res.data.timeStamp,
                                                signType: res.data.signType,
                                                success: () => {
                                                    wx.redirectTo({
                                                        url: '/pages/pay_success/pay_success?order_id=' + that.data.order_id
                                                    })
                                                },
                                                fail: () => {
                                                    that.cancelOrder()
                                                    toast({title: '支付失败'}, () => {
                                                        wx.switchTab({
                                                            url: '/pages/index/index'
                                                        })
                                                    })
                                                }
                                            })
                                        } else {
                                            wx.redirectTo({
                                                url: '/pages/pay_success/pay_success?order_id=' + that.data.order_id
                                            })
                                        }
                                    } else {
                                        wx.showToast({
                                            title: res.msg,
                                            icon: 'none'
                                        })
                                    }
                                }
                            }, 1);
                        }
                    })
                } else {//这里是点击了取消以后
                    console.log('用户点击取消');
                    return false;
                }
            }
        })
    },
    account_chongzhi: function () {
        wx.navigateTo({
            // url: '/pages/account_chongzhi/account_chongzhi',
            url: '/pages/group-buying/group-buying?event=account',
        })
    },
    setPayType: function (e) {
        var type = e.currentTarget.dataset.type;
        this.setData({
            pay_type: type
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var order_id = options.order_id || 0,
            user = wx.getStorageSync('user');
        this.setData({
            order_id: order_id,
            user: user
        });
        this.getOrder();
        EventBus.$on('accountSuccess', this.initAccount)
    },
    onUnload() {
        EventBus.$off('accountSuccess', this.initAccount)
    },

    initAccount(data) {
        const {money} = data
        const {user} = this.data
        this.setData({
            user: {...user, money}
        })
    },
    cancelOrder() {
        const {order_id} = this.data
        app.ajax({
            url: "/api/user/canalOrder",
            data: {order_id},
            success: (resp) => {
                console.log(resp, '取消订单')
            }
        })
    },

    getOrder: function () {
        app.ajax({
            url: '/api/user/payOrder',
            data: {
                id: this.data.order_id
            },
            success: res => {
                console.log(res, 'orderInfo')
                if (res.code == 1) {
                    var coupon_id = 0,
                        coupon_sub = 0,
                        vip_sub = 0,
                        pay_price = 0,
                        yj_price = parseFloat(res.data.yj_price),
                        total_price = parseFloat(res.data.total_price);
                    // if (res.data.coupons.length > 0) {
                    //     coupon_sub = parseFloat(res.data.coupons[0].money);
                    //     coupon_id = res.data.coupons[0].id;
                    // }
                    pay_price = total_price - coupon_sub;

                    var rate = parseFloat(res.data.discount_rate);
                    // if (rate > 0) {
                    //     vip_sub = pay_price * (10 - rate) / 10;
                    //     vip_sub = vip_sub.toFixed(2);
                    //     vip_sub = parseFloat(vip_sub);
                    // }
                    pay_price = pay_price - vip_sub;
                    // pay_price = pay_price + yj_price;
                    pay_price = pay_price.toFixed(2);
                    console.log(pay_price, "canshu1");
                    if (!res.data.paytips) {
                        res.data.paytips = '无'
                    }
                    this.setData({
                        order: res.data,
                        coupon_id: coupon_id,
                        coupon_sub: coupon_sub,
                        vip_sub: vip_sub,
                        pay_price: pay_price,
                        base_price: pay_price,
                    })
                    this.initCoupon()

                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            }
        }, 1);
    },
})
